package com.useeinfo.oa.open.Infrastructure.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.exception.MyException;
import com.useeinfo.oa.common.exception.dto.ExceptionDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.common.utils.exception.DefaultJudgmentViewFactory;
import com.useeinfo.oa.common.utils.exception.JudgmentViewFactory;
import com.useeinfo.oa.common.utils.httpJson.JudgmentJson;
import com.useeinfo.oa.common.utils.httpJson.MyJudgmentJson;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 统一的异常处理
 *
 * @author GeniusJ
 * @email 975473185@qq.com
 * @date 2017-11-19
 * @time 21:00
 */
@Component
public class MyHandlerExceptionResolverInterceptor implements HandlerExceptionResolver {
    private static Logger log = Logger.getLogger(MyHandlerExceptionResolverInterceptor.class);

    private JudgmentJson judgmentJson = new MyJudgmentJson();

    private JudgmentViewFactory judgmentViewFactory = new DefaultJudgmentViewFactory();


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        log.error("ExceptionAspect 捕获的异常：", ex);
        ExceptionDto exceptionDto = judgmentViewFactory.getViewDetailFactory(ex);
        //判断是否为ajax请求
        if(judgmentJson.isJson(request)){
            //重写返回结果集
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(exceptionDto.getResultEnums().value());

            try {
                PrintWriter out= response.getWriter();
                out.print(new ObjectMapper().writeValueAsString(ResultUtil.exception(exceptionDto.getMsg())).toString());
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            ModelAndView modelAndView=new ModelAndView();
            modelAndView.setViewName(exceptionDto.getView());
            modelAndView.getModelMap().put("exception", exceptionDto);
            return modelAndView;
        }
    }
}
